package com.ryujung.binary_tree.leetCode_687;

public class TryMyself {
    int count = 0;//声明全局最大值,记录过根节点或者之过子节点的最大单值长度

    public int longestUnivaluePath(TreeNode root) {
        if(root!=null)pathHelper(root);
        return count;
    }

    public int pathHelper(TreeNode root){
        if (root == null)
            return 0;

        int left = pathHelper(root.left);
        int right = pathHelper(root.right);

        //如果值不相等,则抛弃之前记录的长度,相等则继续累加.
        left = root.left != null && root.left.val == root.val ? left + 1 : 0;
        right = root.right != null && root.right.val == root.val ? right + 1 : 0;

        count = Math.max(count,left+right); //记录通过根节点和只通过当前子节点的长度的最大值

        return Math.max(left,right);
    }
}